// pages/cart/cart.js
import {
  getAddress,
  changeCart,
  getCartList,
  addOrder
} from '../../network/index.js';
const {
  globalData
} = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url_pre: globalData.BASE_URL,
    cartList: [],
    total: 0,
    page: 1,
    pageSize: 10,
    isOK: false,
    priceToast: 0,
    addressId: "",
    address: "",
    name: "",
    phone: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init();
  },
  onShow() {},
  // 初始化页面
  init() {
    this.setData({
      isOK: false,
      cartList: [],
      total: 0,
      page: 1,
      pageSize: 10,
      priceToast: 0,
      address: "",
      name: "",
      phone: "",
    });
    this.getCartList();
    this.getAddress(this.data.addressId);
  },

  // 提交订单
  async onSubmit() {
    const {
      cartList,
      priceToast,
      address,
      name,
      phone
    } = this.data;
    // 没有商品，那就没有得选了
    if (cartList.length <= 0) {
      return wx.showToast({
        title: '请先添加商品到购物车',
        icon: 'none'
      })
    }
    // 找出所有被选中的id 数组
    const carts = cartList.filter((item) => item.select).map((item) => item.id);
    if (carts.length <= 0 || !priceToast) {
      return wx.showToast({
        title: '请先选择商品',
        icon: 'none'
      })
    }
    // 提交订单所需参数
    const params = {
      carts,
      address,
      name,
      phone,
      total_price: priceToast
    };
    const {
      id
    } = await addOrder(params);
    this.init();
    // 前往支付页面
    wx.navigateTo({
      url: `../pay/pay?id=${id}`,
    });
  },

  // 更改了选择
  changeSelect(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const {
      cartList
    } = this.data;
    this.setData({
      ["cartList[" + index + "].select"]: !cartList[index].select
    })
    // 每次选择改变时调用合计
    this.sumPrice();
  },

  // 计算合计金额
  sumPrice() {
    const {
      cartList
    } = this.data;
    const priceToast = cartList.reduce((total, currentValue, currentIndex, arr) => {
      let num = 0;
      if (currentValue.select) {
        num = currentValue.goods_price * currentValue.goods_num;
      }
      return total + num;
    }, 0);
    this.setData({
      priceToast
    })
  },
  // 加
  onPlus(event) {
    const {
      index,
      goods_num,
      goods_id
    } = event.currentTarget.dataset;
    this.changeCart(index, goods_id, goods_num, "add");
  },
  // 减
  onMinus(event) {
    const that = this;
    const {
      index,
      goods_num,
      goods_id
    } = event.currentTarget.dataset;
    if (goods_num <= 1) {
      wx.showModal({
        title: '提示',
        content: '确定删除吗？确认将删除并刷新页面！',
        async success(res) {
          if (res.confirm) {
            that.changeCart(index, goods_id, goods_num, "minus");
          }
        }
      })
    } else {
      this.changeCart(index, goods_id, goods_num, "minus");
    }
  },

  // 更改了购物车
  changeCart(index, goods_id, goods_num, mode) {
    changeCart({
      goods_id,
      mode
    }).then(() => {
      const num = mode === "add" ? goods_num + 1 : goods_num - 1;
      if (num <= 0) {
        this.init();
      } else {
        this.setData({
          ["cartList[" + index + "].goods_num"]: num
        })
        // 每次数量改变时调用合计
        this.sumPrice();
      }
    })
  },

  // 获取购物车列表
  async getCartList() {
    wx.showLoading({
      title: '加载中',
    })
    await getCartList({
      page: this.data.page,
      pageSize: this.data.pageSize
    }).then((result) => {
      const {
        items,
        total
      } = result;
      // 整理接受的数据
      const data = items.map(item => {
        item.goods_urls = this.data.url_pre + item.goods_urls[0];
        item.select = false;
        return item;
      })
      // 与之前数据合并
      const cartList = [...this.data.cartList, ...data];
      // 更新视图
      this.setData({
        total,
        page: this.data.page++,
        cartList
      })
      // 计算合计
      this.sumPrice();
    })
    if (this.data.total <= this.data.cartList.length) {
      this.setData({
        isOK: true
      });
    }
    wx.hideLoading();
  },
  // 获取地址
  getAddress(addressId) {
    getAddress({
      id: addressId
    }).then((result) => {
      if (result <= 0) {
        return;
      }
      console.log(result)
      const {
        id,
        province,
        city,
        country,
        detailed,
        name,
        phone
      } = result[0];
      this.setData({
        addressId: id,
        address: `${province}-${city}-${country}-${detailed}`,
        name,
        phone
      })
    })
  },

  // 前往地址列表更改地址 `${path}?fromPage=me`
  toAddresList() {
    const that = this;
    const {
      addressId
    } = this.data;
    if (addressId) {
      wx.navigateTo({
        url: `../addressList/addressList?fromPage=order&addressId=${addressId}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          bingAdress({
            data
          }) {
            that.setData({
              addressId: data
            })
            that.getAddress(data);
          },
        },
      });
    }else{
      wx.navigateTo({
        url: `../addressList/addressList?fromPage=order`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          bingAdress({
            data
          }) {
            that.setData({
              addressId: data
            })
            that.getAddress(data);
          },
        },
      });
    }

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.init();
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isOK) {
      return;
    }
    this.getCartList();
  },
})